package com.example.booksearch;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

// 定义 Servlet 的映射路径
@WebServlet("/BookSearchServlet")
public class BookSearchServlet extends HttpServlet {
    // 模拟的图书数据列表（实际应用中应从数据库获取）
    private static final List<Book> bookList = new ArrayList<>();

    static {
        bookList.add(new Book("Java Core", "John Doe"));
        bookList.add(new Book("JavaScript Advanced", "Jane Smith"));
        bookList.add(new Book("Web Development Basics", "Bob Johnson"));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应头，允许跨域请求
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setContentType("application/json");

        // 获取前端传递的关键词参数
        String keyword = request.getParameter("keyword");

        // 模拟根据关键词查询图书数据
        List<Book> result = new ArrayList<>();
        if (keyword!= null &&!keyword.isEmpty()) {
            for (Book book : bookList) {
                if (book.title.contains(keyword)) {
                    result.add(book);
                }
            }
        }

        // 将查询结果转换为 JSON 格式字符串
        String jsonResponse = convertToJson(result);

        // 将 JSON 数据写回响应
        PrintWriter out = response.getWriter();
        out.print(jsonResponse);
        out.flush();
    }

    // 简单的将图书列表转换为 JSON 格式字符串的方法（实际应用中可使用 JSON 库）
    private String convertToJson(List<Book> books) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < books.size(); i++) {
            Book book = books.get(i);
            json.append("{\"title\":\"").append(book.title).append("\",\"author\":\"").append(book.author).append("\"}");
            if (i < books.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");
        return json.toString();
    }

    // 图书类
    private static class Book {
        String title;
        String author;

        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
    }
}